/*
 * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package com.oracle.svm.hosted.webimage.wasm.phases;

import java.util.function.Function;

import org.graalvm.word.LocationIdentity;

import jdk.graal.compiler.core.common.memory.BarrierType;
import jdk.graal.compiler.core.common.memory.MemoryOrderMode;
import jdk.graal.compiler.nodes.NodeView;
import jdk.graal.compiler.nodes.StructuredGraph;
import jdk.graal.compiler.nodes.ValueNode;
import jdk.graal.compiler.nodes.calc.BinaryArithmeticNode;
import jdk.graal.compiler.nodes.java.AbstractCompareAndSwapNode;
import jdk.graal.compiler.nodes.java.LoweredAtomicReadAndAddNode;
import jdk.graal.compiler.nodes.java.LoweredAtomicReadAndWriteNode;
import jdk.graal.compiler.nodes.memory.FixedAccessNode;
import jdk.graal.compiler.nodes.memory.ReadNode;
import jdk.graal.compiler.nodes.memory.WriteNode;
import jdk.graal.compiler.nodes.memory.address.AddressNode;
import jdk.graal.compiler.nodes.spi.CoreProviders;
import jdk.graal.compiler.phases.BasePhase;

/**
 * Replaces atomic nodes with nodes that have the same behavior in an environment without
 * concurrency and thus don't require atomicity.
 * <p>
 * In general, images generated by Web Image are single-threaded. For both JS and WasmGC, sharing
 * objects outside their execution thread is not possible so multi-threading does not make sense
 * there at all.
 */
public abstract class SingleThreadedAtomicsPhase extends BasePhase<CoreProviders> {
    @Override
    protected void run(StructuredGraph graph, CoreProviders context) {
        for (AbstractCompareAndSwapNode cas : graph.getNodes(AbstractCompareAndSwapNode.TYPE)) {
            processCAS(context, cas);
        }

        // Replace read and write (getAndSet) with individual read and write
        for (LoweredAtomicReadAndWriteNode readAndWriteNode : graph.getNodes(LoweredAtomicReadAndWriteNode.TYPE)) {
            processReadAndWrite(readAndWriteNode);
        }

        // Replace read and write (getAndAdd) with individual read, add, and write
        for (LoweredAtomicReadAndAddNode readAndAddNode : graph.getNodes(LoweredAtomicReadAndAddNode.TYPE)) {
            processReadAndAdd(readAndAddNode);
        }
    }

    /**
     * Replace the given compare and swap node with equivalent non-atomic node(s).
     */
    protected abstract void processCAS(CoreProviders providers, AbstractCompareAndSwapNode cas);

    protected void processReadAndWrite(LoweredAtomicReadAndWriteNode readAndWriteNode) {
        replaceWithReadAndWrite(readAndWriteNode.graph(), readAndWriteNode, value -> readAndWriteNode.getNewValue());
    }

    protected void processReadAndAdd(LoweredAtomicReadAndAddNode readAndAddNode) {
        StructuredGraph graph = readAndAddNode.graph();
        replaceWithReadAndWrite(graph, readAndAddNode, value -> BinaryArithmeticNode.add(graph, value, readAndAddNode.delta(), NodeView.DEFAULT));
    }

    /**
     * Replaces an atomic ReadModifyWrite node with a separate read and subsequent write.
     *
     * @param readWriteNode The ReadModifyWrite node
     * @param readToWriteValue Given the read result, produces the value to write.
     */
    private static void replaceWithReadAndWrite(StructuredGraph graph, FixedAccessNode readWriteNode, Function<ReadNode, ValueNode> readToWriteValue) {
        AddressNode address = readWriteNode.getAddress();
        LocationIdentity locationIdentity = readWriteNode.getLocationIdentity();
        BarrierType barrierType = readWriteNode.getBarrierType();
        MemoryOrderMode memoryOrder = MemoryOrderMode.VOLATILE;

        ReadNode readNode = graph.add(new ReadNode(address, locationIdentity, readWriteNode.stamp(NodeView.DEFAULT), barrierType, memoryOrder));
        ValueNode newValue = readToWriteValue.apply(readNode);
        WriteNode writeNode = graph.add(new WriteNode(address, locationIdentity, newValue, barrierType, memoryOrder));

        graph.replaceFixedWithFixed(readWriteNode, readNode);
        graph.addAfterFixed(readNode, writeNode);
    }
}
